from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.generics import ListCreateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKU, SKUImage
from meiduo_mall_admin.meiduo_admin.serializers import GoodSkuSerializer, PagNun, SkuInfoSerializer


class SKUIdListView(ListAPIView):
  # 获取所有的SKU
  queryset = SKU.objects.all()
  serializer_class = SkuInfoSerializer


# -----------图片管理--------
class SkuImagesView(ModelViewSet):
  queryset = SKUImage.objects.all()
  serializer_class = GoodSkuSerializer
  pagination_class = PagNun

  def create(self, request, *args, **kwargs):
    from fdfs_client.client import Fdfs_client
    # from django.conf import settings
    client = Fdfs_client('utility/fastdfs/client.conf')
    data = request.FILES.get('image')
    # 上传图片到fastDFS
    res = client.upload_by_buffer(data.read())
    # 判断是否上传成功
    if res['Status'] != 'Upload successed.':
      return Response(status=403)
    # 获取上传后的路径
    image_url = res['Remote file_id']
    # 获取sku_id
    sku_id = request.data.get('sku')
    # 保存图片
    img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
    # 返回结果
    return Response(
      {
        'id': img.id,
        'sku': sku_id,
        'image': img.image.url
      },
      status=201  # 前端需要接受201状态
    )

  def update(self, request, *args, **kwargs):
    # pk = self.get_object().pk
    pk = kwargs['pk']
    sku_id = request.data.get('sku')
    image = request.data.get('image').read()

    from fdfs_client.client import Fdfs_client
    client = Fdfs_client('utility/fastdfs/client.conf')

    # 删除之前的图片，然后在更新
    sku_image_conn = SKUImage.objects.get(id=pk)
    old_image_url = str(sku_image_conn.image)
    client.delete_file(old_image_url)

    res = client.upload_appender_by_buffer(image)

    # 判断是否上传成功
    if res['Status'] != 'Upload successed.':
      return Response(status=403)

    image_url = res['Remote file_id']
    sku_image_conn = SKUImage.objects.get(id=pk)
    sku_image_conn.image = image_url
    sku_image_conn.save()
    return Response(
      {
        'id': sku_image_conn.id,
        'sku': sku_id,
        'image': sku_image_conn.image.url
      },
      status=201  # 前端需要接受201状态码
    )

  def destroy(self, request, *args, **kwargs):
    pk = kwargs['pk']
    skuimage_conn = SKUImage.objects.get(pk=pk)
    image_url = str(skuimage_conn.image)

    from fdfs_client.client import Fdfs_client
    client = Fdfs_client('utility/fastdfs/client.conf')
    client.delete_file(image_url)

    skuimage_conn.delete()

    return Response(status=status.HTTP_204_NO_CONTENT)





